package wsepForum.ui.swing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import wsepForum.network.client.GUIController;
import wsepForum.network.common.GUIRequest;
import wsepForum.network.common.GUIRequest.RequestType;
import wsepForum.ui.swing.innerPanels.AInnerPanel;
import wsepForum.ui.swing.outerPanels.AOuterPanel;
import wsepForum.ui.swing.outerPanels.GuestPanel;
import wsepForum.ui.swing.outerPanels.MemberPanel;
import wsepForum.ui.swing.workers.ForumWorker;

public class ForumFrame  extends JFrame implements SetSwitcher {
	
	private static final long serialVersionUID = 247815372550744394L;
	private AOuterPanel outerPanel;
	protected GUIController connection;
	private SetType currentSet;

	public ForumFrame(GUIController controller){
		super("WSEP Forum");
		this.currentSet = SetType.GUEST;
		this.connection = controller;
		
		final JButton forceLogoutButton = new JButton();
		forceLogoutButton.setVisible(false);
		forceLogoutButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				ForumWorker<JComponent> logoutWorker = new ForumWorker<JComponent>(connection){
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						this.controller.addInitialRequest(new GUIRequest(RequestType.LOGOUT, new Object[]{} ,0), this);
						inbox.take();
						JOptionPane.showMessageDialog(null, "due to a change in your privileges, you where disconnected.\nplease log in again.", "Disconnection",JOptionPane.ERROR_MESSAGE);
						return null;
					}
					@Override
					public void done(){
						switchSet(SetType.GUEST);
						forceLogoutButton.doClick();
					}
				};
			
			logoutWorker.execute();
			}
		});
		this.add(forceLogoutButton);
		
		forceLogoutButton.doClick();
		this.getContentPane().setLayout(null);
		this.setBounds(100, 100, 761, 527);
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.outerPanel = new GuestPanel(controller,this);
		this.getContentPane().add(this.outerPanel);
	}
	

	public void draw() {
		this.setVisible(true);
	}

	public void swapPanel(AOuterPanel panel) {
		
		if (panel != null) {
			panel.setVisible(true);
			this.getContentPane().removeAll();
			this.getContentPane().add(panel);
			this.outerPanel = panel;
			this.repaint();
		}
	}

	public GUIController getConnection(){
		return this.connection;
	}


	@Override
	public void switchSet(SetType type) {
		this.currentSet = type;
		switch(type) {
		case GUEST:
			swapPanel(new GuestPanel(this.connection,this));
			break;
		default:
			swapPanel(new MemberPanel(this.connection, this));
			break;
		}
	}


	@Override
	public SetType getSet() {
		return this.currentSet;
	}

}
